/*
 * @Description: 
 * @version: 
 * @Author: 171
 * @Date: 2022-09-04 18:58:16
 * @LastEditors: 171
 * @LastEditTime: 2022-09-05 15:30:17
 */
import CryptoJS from 'crypto-js'
 
export interface CrypotoType {
  encrypt: any
  decrypt: any
}
 
type WordArray = CryptoJS.lib.WordArray
 

export default class Crypoto implements CrypotoType {
  key: WordArray; 
  iv: WordArray; 
  constructor(secretKey: string, secretKeyOffset: string){
    this.key = CryptoJS.enc.Utf8.parse(secretKey); // 十六位十六进制数作为密钥
    this.iv = CryptoJS.enc.Utf8.parse(secretKeyOffset) // 十六位十六进制数作为密钥偏移量
  }
 
  /* 加密 */
  encrypt (word: any) {
    const srcs = CryptoJS.enc.Utf8.parse(word)
    const encrypted = CryptoJS.AES.encrypt(srcs, this.key, { iv: this.iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
    return encrypted.ciphertext.toString().toUpperCase()
  }
 
  /* 解密 */
  decrypt (word: any) {
    const encryptedHexStr = CryptoJS.enc.Hex.parse(word)
    const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
    const decrypt = CryptoJS.AES.decrypt(srcs, this.key, { iv: this.iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
    const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
    return decryptedStr.toString()
  }
}